package com.blockchain.anti_counterfeiting.api;

import com.blockchain.sql.DBConnect;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.UUID;

@WebServlet(urlPatterns = "/register")
public class Register extends HttpServlet {
    private void SQLConnect(String users, String email, String upassword, String phone) throws ClassNotFoundException, SQLException {
        try{
            UUID uuid = UUID.randomUUID();
            Connection conn = new DBConnect().getConnection();
            PreparedStatement stmt = conn.prepareStatement("insert into user values(?,?,?,?,?)");

            stmt.setString(1,users);
            stmt.setString(2,upassword);
            stmt.setString(3,email);
            stmt.setString(4,phone);
            stmt.setString(5,uuid.toString());

            stmt.executeUpdate();

            stmt.close();
            conn.close();
        } catch (SQLException e) {
            throw new SQLException(e.getMessage());
        }
    }
    public void doGet(HttpServletRequest req, HttpServletResponse res) throws IOException {
        res.setStatus(HttpServletResponse.SC_MOVED_TEMPORARILY);
    }
    public void doPost(HttpServletRequest req, HttpServletResponse res) throws IOException {
        res.setContentType("application/json");
        PrintWriter out = res.getWriter();
        String users = req.getParameter("users");
        String email = req.getParameter("email");
        String password = req.getParameter("password");
        String phone = req.getParameter("phone");
        try {
            SQLConnect(users,email, String.valueOf(password.hashCode()),phone);
        } catch (Exception e) {
            res.setStatus(HttpServletResponse.SC_BAD_REQUEST);
        }
        destroy();
    }
    public void destroy() {
        super.destroy();
    }
}
